package com.zookeeper.zktest;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author : hebad90@163.com
 * @Date : 2014/11/18 22:47
 * @From : javalearn
 */
public class ZKTest implements Watcher {
    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        new ZKTest(latch);
        latch.await();
    }

    private ZooKeeper zk;
    private String root = "/locks";
    private String node=null;
    CountDownLatch latch =null;

    public ZKTest(CountDownLatch latch) throws Exception {
        zk = new ZooKeeper("localhost:2181", 1000, this);
        this.latch=latch;
    }

    @Override
    public void process(WatchedEvent e) {
        System.out.println(e.getType() + "-" + e.getState());
        try {
            if (e.getType() == Event.EventType.None) {
                System.out.println("zk已经建立连接");

                Stat s = zk.exists(root, false);
                if(s==null){
                    System.out.println("创建根结点"+root);
                    zk.create(root,"root".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
                    System.out.println("创建根结点完成");
                }

                if(node==null){
                    System.out.println("创建节点....");
                    node = zk.create(root+"/lock_", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
                    System.out.println("创建节点完成....");
                }
            }

            getLock();

        } catch (KeeperException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public void getLock() throws Exception{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> list = zk.getChildren(root, true);
        System.out.println(root + "发现当前的子节点个数为：" + list.size());

        List<String> children = zk.getChildren(root,true);
        Object[] arr = children.toArray();
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        if(node.equals("/locks/"+arr[0])){
            System.out.println("获取锁-"+format.format(new Date()));
            Thread.sleep(20000);
            zk.close();
            System.out.println("释放锁-"+format.format(new Date()));
            latch.countDown();
        }else{
            System.out.println("没有获取锁，继续等待");
        }
    }
}
